#include "mymqtt.h"
#include "ui_mymqtt.h"



MyMqtt::MyMqtt(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyMqtt)
{
    ui->setupUi(this);
    //client = new QMQTT::Client(QHostAddress("192.168.28.113"),1883);

    client = new QMQTT::Client;   //可以加括号,相同:client = new QMQTT::Client();


    QString data;
        QFile file (":/node.json");
        if(!file.open(QIODevice::ReadOnly))
            {
                qDebug()<<"open read error";
                return;
            }
        QTextStream stream(&file);
        stream.setCodec("UTF-8");// 设置读取编码是UTF8
        data = stream.readAll();
        file.close();//关闭文件
    QJsonParseError jsonerror;
    QJsonDocument doc = QJsonDocument::fromJson(data.toLatin1(), &jsonerror);
    QJsonObject object = doc.object();
    QJsonObject obj = object.value("mqtt_server").toObject();
    QString addrnum = obj.value("addr").toVariant().toString();
    QString portnum = obj.value("port").toVariant().toString();
    qDebug()<<"addr:"<<addrnum<<" "<<"port:"<<portnum;

    mqttInit(addrnum,portnum);


    //信号槽连接
    connect(client,SIGNAL(connected()),this,SLOT(doConnected()));
    connect(client,SIGNAL(disconnected()),this,SLOT(doDisConnected()));
    connect(client,SIGNAL(subscribed(const QString&, const quint8)),
            this,SLOT(doSubscribed(const QString&, const quint8)));
    connect(client,SIGNAL(received(QMQTT::Message)),
            this,SLOT(doDataReceived(QMQTT::Message)));


}

void MyMqtt::doConnected()
{
    qDebug()<<"MQTT connect success";
    emit mqttstatesignalon();
    client->subscribe("/app/data/up");//设置topic接收主题

}

void MyMqtt::doDisConnected()
{

    qDebug()<<"mqtt disconnected";
    emit mqttstatesignaloff();

}

quint16 MyMqtt::publish(QString data)
{
    QMQTT::Message message(0, "/app/data/down", data.toUtf8());//设置topic发送主题
    client->publish(message);
}

void MyMqtt::detectState()
{
    int state = client->connectionState();
    if(state != 2)
    {
        qDebug()<<"mqtt connect error! errornum:"<< state;
        client->disconnectFromHost();
        //QTimer::singleShot(3000, this, SLOT(detectState()));
    }
}

void MyMqtt::mqttInit(QString ip, QString port)
{

    client->disconnectFromHost();
    client->setHost(QHostAddress(ip));
    client->setPort(port.toInt());
    client->setClientId("clientid");
    client->setAutoReconnectInterval(3);
    client->setAutoReconnect(false);
    client->connectToHost();
    QTimer::singleShot(3000, this, SLOT(detectState()));
}

void MyMqtt::cancelconnect()
{
    client->disconnectFromHost();
}

void MyMqtt::doDataReceived(QMQTT::Message message)
{
    qDebug()<<"topic="<<message.topic();
    rawdata = message.payload();
    qDebug()<<"mqtt:msg="<<rawdata;
    emit upsignal(rawdata);

//        if(key==101)//modbus环境温度
//        if(key==102)//modbus环境湿度
//        if(key==103)//modbus空调开关(控制类不处理)
//        if(key==104)//modbus空调温度(没开发接口)
//        if(key==105)//modbus灯(控制类不处理)
//        if(key==301)//STM32温度或湿度或火焰
//        if(key==302)//STM32电池(没开发接口)
//        if(key==303)//STM32灯(控制类不处理)

}


void MyMqtt::doSubscribed(const QString& topic, const quint8 qos)
{

    qDebug()<<"订阅主题:"<<topic;
}



MyMqtt::~MyMqtt()
{
    if(client->isConnectedToHost())
        client->disconnectFromHost();

    delete ui;
}
